//1.从pinia中导入defineStore函数
import { defineStore } from 'pinia';
import request from '../utils/request';

//2.定义用户状态管理实例并导出
export const useUserStore = defineStore("userStore", {
    //1.state属性 保存数据状态
    state: () => ({ //保存用户登录状态
        userinfo: {
            uid:'',
            username: "",
            imgPath: "",
            password:'',
            type:'',
        },
        token:"",
        isLogin: false,
    }),
    //计算数据:使用state中数据，根据state中原始数据派生出新的数据。(不推荐修改state中数据)
    getters: {
        //判断用户是否登录
        checkLogin: (state) => state.userinfo.username != null && state.userinfo.username != "",
        // getUsername: (state) => state.userinfo.username, //获取用户名
        // getImgPath:(state) => state.userinfo.imgPath //获取登录用户头像地址
        isToken:(state) => state.token != null && state.token != "",
    },
    actions: { //修改state中数据
        /**
         * 用户登录方法，如果登录成功则把用户信息保存到state中相关属性中
         */
        async login(userinfo: any) {
            //1.发送请求实现登录
            let response = await request.post("/login/login", userinfo);
            if (response.data.success) {
                this.userinfo.uid = response.data.data.uid;
                this.userinfo.username = response.data.data.username;
                this.userinfo.imgPath = response.data.data.imgPath;
                this.userinfo.password = response.data.data.password;
                this.userinfo.type = response.data.data.type;
                
            } else { //登录失败
                this.userinfo.uid = '';
                this.userinfo.username = "";
                this.userinfo.imgPath = "";
                this.userinfo.password = '';
                this.userinfo.type = '';
            }
            return response.data;
        },
        LogOut(){
            this.userinfo.uid = '';
            this.userinfo.imgPath='';
            this.userinfo.username='';
            this.userinfo.password = '';
            this.userinfo.type = '';
            this.token='';
        },
        /**
         * 给token设置
         */
        setToken(token:any){
            this.token = token;
        }
    },
    // persist: true, //默认把pinia数据保存到localStorage中 
    persist: {
        // enabled: true,// 开启持久化存储
        storage: sessionStorage, // 存储位置，默认为 localStorage
    }

})